<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者ID" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="统计日期" prop="summaryDate">
        <el-date-picker clearable
          v-model="queryParams.summaryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择统计日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button 
          v-if="queryParams.summaryDate" 
          type="warning" 
          icon="el-icon-edit" 
          size="mini" 
          @click="handleFix">修复</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          v-hasPermi="['system:summary:add']"
        >刷新数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:summary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="summaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者ID" align="center" prop="patientId" />
      <el-table-column label="统计日期" align="center" prop="summaryDate" />
      <el-table-column label="入量" align="center" prop="totalIntake" />
      <el-table-column label="出量" align="center" prop="totalOutput" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仅统计当天有数据的患者，补录后自动更新对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="写入时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择写入时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修复确认对话框 -->
    <el-dialog
      title="警告"
      :visible.sync="fixDialogVisible"
      width="300px"
      append-to-body
      :before-close="handleFixDialogClose"
    >
      <span>确定要修复 {{ queryParams.summaryDate }} 的数据吗？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleFixDialogClose">取消</el-button>
        <el-button type="primary" @click="handleFix">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSummary, getSummary, delSummary, addSummary, updateSummary } from "@/api/system/summary";

export default {
  name: "Summary",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仅统计当天有数据的患者，补录后自动更新表格数据
      summaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示修复确认弹出层
      fixDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: null,
        totalIntake: null,
        totalOutput: null,
        summaryDate: null,
        createdTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createdTime: [
          { required: true, message: "写入时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询仅统计当天有数据的患者，补录后自动更新列表 */
    getList() {
      this.loading = true;
      listSummary(this.queryParams).then(response => {
        this.summaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        patientId: null,
        totalIntake: null,
        totalOutput: null,
        summaryDate: null,
        createdTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.patientId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 刷新数据按钮操作 (替换原来的新增按钮) */
    handleRefresh() {
      this.getList();
      this.$modal.msgSuccess("数据刷新成功");
    },
    /** 新增按钮操作 - 保留但已不显示在界面上 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仅统计当天有数据的患者，补录后自动更新";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const patientId = row.patientId || this.ids
      getSummary(patientId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改仅统计当天有数据的患者，补录后自动更新";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.patientId != null) {
            updateSummary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSummary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const patientIds = row.patientId || this.ids;
      this.$modal.confirm('是否确认删除患者ID为"' + patientIds + '"的数据项？').then(function() {
        return delSummary(patientIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/summary/export', {
        ...this.queryParams
      }, `summary_${new Date().getTime()}.xlsx`)
    },
    /** 修复按钮操作 */
    handleFix() {
      if (!this.queryParams.summaryDate) {
        this.$modal.msgError("请先选择统计日期");
        return;
      }
      
      this.$confirm(
        `确定要修复 ${this.queryParams.summaryDate} 的数据吗？`, 
        '警告', 
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 这里可以调用修复数据的API
        // 示例：fixSummaryData(this.queryParams.summaryDate)
        this.loading = true;
        setTimeout(() => {  // 模拟API调用
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess(`${this.queryParams.summaryDate} 数据修复成功`);
        }, 1000);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修复'
        });
      });
    },
    /** 修复对话框关闭处理 */
    handleFixDialogClose() {
      this.fixDialogVisible = false;
    }
  }
};
</script>
